package com.ld.bisystem.util;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ListUtil {

    /**
     * 对象值映射
     * @param list
     * @param key
     * @param <E>
     * @return
     */
    public static <E> List<E> mapValue(List list, String key){
        List<E> vals = (List<E>) list.stream().map(v -> ReflectionUtil.invokeGetter(v,key)).collect(Collectors.toList());
        return vals;
    }

    /**
     * 数组拷贝
     * @param list
     * @param size
     * @param <E>
     * @return
     */
    public static  int[] arrCopy(int[] list, int size){
        int[] vs = new int[size];
        for(int i = 0 ; i < size ; i ++){
            vs[i]=list[i];
        }
        return vs;
    }

  public static <E> List<E> objToList(Object val, Class<E> target) {
        List list =  new LinkedList<>();
        objToList(val,target,list);
        return list;
  }


    /**
     * 集合一维
     * @return
     */
    private static void listMapOne(Collection cols,Collection box) {

        for (Object col : cols) {
          if(col instanceof Collection){
              listMapOne((Collection) col,box);
          }else{
              box.add(col);
          }
        }

    }


    /**
     * 集合一维
     * @return
     */
    public static Collection listMapOne(Collection cols) {

        LinkedList list = new LinkedList<>();

        listMapOne(cols,list);
        return list;

    }
    /**
     * 复杂对象变换集合
     * @param val
     * @param target
     * @param list
     * @param <E>
     */
    private static <E> void objToList(Object val,Class<E> target,List list){

        if(val instanceof Map){
            Map map = (Map)val;
            Object v =  map.values();
            objToList(v,target,list);
        }else if(val instanceof Collection){
            Collection cols  = (Collection) val;
              for (Object col : cols) {
                  objToList(col,target,list);
              }
        }else if(target.isAssignableFrom(val.getClass())){
            list.add(val);
        }


    }


}
